'''
Created on 17/08/2010

@author: eh01
'''
from datastore.resource import Resource
from datastore.spaces import Spaces
from services.makohttptemplate import MakoHTTPTemplate
from xml.dom import minidom
import os
import unittest
from spear.a2p_service import A2PService
from adaptor.services.application_service import ApplicationService
from datastore.uri import Uri
import adaptor


class ApplicationServiceTest(unittest.TestCase):

    SITE_TEMPLATE_FILE_PATH = '../../../sites/adaptor/templates/adaptor-template.xml'
    SITE_TEMPLATE_FILE_PATH_WHEN_RUNNING_FROM_ANT = '../sites/adaptor/templates/adaptor-template.xml'
    TEMPLATE_DIRECTORY = '../../../sites/adaptor/templates'
    TEMPLATE_DIRECTORY_WHEN_RUNNING_FROM_ANT = '../sites/adaptor/templates'
    
    def setUp(self):
        pass


    def tearDown(self):
        pass


    def test_template(self):
        site_template_res = Resource(type="temp")
        if os.path.isfile(ApplicationServiceTest.SITE_TEMPLATE_FILE_PATH):
            site_template_res.load_from_file(ApplicationServiceTest.SITE_TEMPLATE_FILE_PATH)
            template_dir =  ApplicationServiceTest.TEMPLATE_DIRECTORY
        else:
            site_template_res.load_from_file(ApplicationServiceTest.SITE_TEMPLATE_FILE_PATH_WHEN_RUNNING_FROM_ANT)
            template_dir =  ApplicationServiceTest.TEMPLATE_DIRECTORY_WHEN_RUNNING_FROM_ANT        
        spaces = Spaces()
        template_res = Resource(type="temp")
        template_res.load_from_file('/'.join([template_dir, 'application.xml']))
        res = Resource(type="term:eplanning/adaptor/application-list/data")
        res.application = {'SPEAR_Reference_Number':'S000001E'}
        res.summary = {'sid002b_status':'Submitted'}
        res.control = {'date_last_modified':'17/08/2010 09:41:51',
                       'state':A2PService.APPSTATE_UPDATINGFROMSPEAR}
        res.applicant_docs = []
        res.council_docs = []
        res.referral_authority_docs = []
        res.objector_docs = []        
        res.h1_header = 'Test Header'
        x = MakoHTTPTemplate(spaces, site_template_res, template_res, res)
        html = raw_xml(x.render().strip())
        
        # Test the app info is rendered
        spear_reference_number_html = '<dt>SPEAR Reference Number:</dt><dd>S000001E</dd>'
        spear_status_html = '<dt>SPEAR Status:</dt><dd>Submitted</dd>'
        last_update_html = '<dt>Last Update from SPEAR:</dt><dd>17/08/2010 09:41:51</dd>'
        app_state_html = '<dt>State:</dt><dd>updatingfromspear</dd>'
        accept_reject_button_html = """<input class="btn" onclick="window.location='/adaptor/accept-reject?spearRef=S000001E';" type="button" value="Accept or Reject SPEAR Application"/>"""
        refer_app_button_html = """<input class="btn" onclick="window.location='/adaptor/refer?spearRef=S000001E';" type="button" value="Refer SPEAR Application"/>"""
        self.assertTrue(spear_reference_number_html in html)
        self.assertTrue(spear_status_html in html)
        self.assertTrue(last_update_html in html)
        self.assertTrue(app_state_html in html)
        
        # Test the accept reject button is displayed and refer not displayed
        self.assertTrue(accept_reject_button_html in html)
        self.assertFalse(refer_app_button_html in html)
        
        # Test the accept reject button is not displayed and refer is displayed 
        res.summary = {'sid002b_status':'Lodged with Responsible Authority'}
        x = MakoHTTPTemplate(spaces, site_template_res, template_res, res)
        html = raw_xml(x.render().strip())
        self.assertFalse(accept_reject_button_html in html)
        self.assertTrue(refer_app_button_html in html)
    
    def test_cb_start(self):
        spaces = Spaces()
        uri = Uri()
        application_service = ApplicationService(spaces=spaces, uri=uri)
        application_service.cb_start(None, None, None)
        self.assertEqual([application_service.cb_get_application], spaces.process[Uri('internal:adaptor/application/')])
    
    def test_cb_get_application_get(self):
        spaces = Spaces()
        uri = Uri()
        application_service = ApplicationService(spaces=spaces, uri=uri)
        res = application_service.cb_get_application(Uri('test/uri'), Spaces.ACTION_GET, None)
        self.assertEqual(None, res)
        
    def test_cb_get_application_put(self):
        spear_reference_number = 'S000001E'
        spaces = Spaces()
        uri = Uri('test/uri')
        res_post = Resource(type='term:base/services/http/post')
        res_post.query_data = {'spearRef':spear_reference_number}
        application_service = ApplicationService(spaces=spaces, uri=Uri())
        
        # app that doesn't exists
        response_uri = application_service.cb_get_application(uri, Spaces.ACTION_PUT, res_post)
        self.assertEqual(uri + 'response', response_uri)
        response_res = spaces.get(response_uri)
        self.assertEqual(Uri('term:eplanning/adaptor/error'), response_res.get_type())
        self.assertEqual(adaptor.ERROR_H1_HEADER, response_res.h1_header)
        self.assertEqual(adaptor.APP_NOT_FOUND_MSG % spear_reference_number, response_res.error)
        
        # app exists but no docs
        app_res = Resource(type="term:eplanning/spear/application")
        app_res.set_metadata(Uri('spearReferenceNumber'), spear_reference_number)
        app_res.control_dict = {}
        app_res.sid002b_dict = {}        
        spaces.put(Uri('spear:app/%s' % spear_reference_number), app_res)
        response_uri = application_service.cb_get_application(uri, Spaces.ACTION_PUT, res_post)
        self.assertEqual(uri + 'response', response_uri)
        response_res = spaces.get(response_uri)
        self.assertEqual([], response_res.applicant_docs)
        self.assertEqual([], response_res.council_docs)
        self.assertEqual([], response_res.referral_authority_docs)
        self.assertEqual([], response_res.objector_docs)
        self.assertEqual(ApplicationService.SPEAR_APPLICATION_HEADER, response_res.h1_header)
        
        # app exists and with docs
        # doc in doc types to display so it will be displayed
        doc_1 = {'sid004_doctype':ApplicationService.DOC_TYPES_TO_DISPLAY[0],
                 'sid004_doc_id':'1',
                 'sid004_owner_type__derived':'Applicant Contact'}
        # doc is PDF, and has attachment in spaces so it will be displayed
        doc_2 = {'sid004_doctype':'Other Document Type',
                 'sid004_doc_id':'2',
                 'sid004_owner_type__derived':'Responsible Authority'}
        doc_2_version = {'sid005a_current_document_format':'PDF'}
        spaces.put(Uri('spear:app-attachment/%s' % '2'), Resource(type='term:eplanning/spear/application-attachment'))
        # doc is PDF but has no owner type so it won't be displayed
        doc_3 = {'sid004_doctype':'Other Document Type',
                 'sid004_doc_id':'3'}
        doc_3_version = {'sid005a_current_document_format':'PDF'}
        spaces.put(Uri('spear:app-attachment/%s' % '3'), Resource(type='term:eplanning/spear/application-attachment'))
        # doc in doc types to display list so it will be displayed
        doc_4 = {'sid004_doctype':ApplicationService.DOC_TYPES_TO_DISPLAY[1],
                 'sid004_doc_id':'4',
                 'sid004_owner_type__derived':'Applicant Contact'}
        doc_4_version = {}
        # doc is PDF but attachment hasn't been downloaded yet, so it won't be displayed
        doc_5 = {'sid004_doctype':'Other Document Type',
                 'sid004_doc_id':'5',
                 'sid004_owner_type__derived':'Applicant Contact'}
        doc_5_version = {'sid005a_current_document_format':'PDF'}        
        app_res.application = {}
        app_res.sid004_dict = {'sid004_attachment_dict_list':[doc_1, doc_2, doc_3, doc_4, doc_5]}
        app_res.sid005a_dict_dict = {'2':doc_2_version,
                                     '3':doc_3_version,
                                     '4':doc_4_version,
                                     '5':doc_5_version}
        spaces.put(Uri('spear:app/%s' % spear_reference_number), app_res)
        response_uri = application_service.cb_get_application(uri, Spaces.ACTION_PUT, res_post)
        self.assertEqual(uri + 'response', response_uri)
        response_res = spaces.get(response_uri)
        self.assertEqual([doc_1, doc_4], response_res.applicant_docs)
        self.assertEqual([doc_2], response_res.council_docs)
        self.assertEqual([], response_res.referral_authority_docs)
        self.assertEqual([], response_res.objector_docs)
        self.assertEqual(ApplicationService.SPEAR_APPLICATION_HEADER, response_res.h1_header)

    def test_cb_get_application_update(self):
        spaces = Spaces()
        uri = Uri()
        application_service = ApplicationService(spaces=spaces, uri=uri)
        response_uri = application_service.cb_get_application(Uri('test/uri'), Spaces.ACTION_UPDATE, None)
        self.assertEqual(None, response_uri)
        
    def test_cb_get_application_delete(self):
        spaces = Spaces()
        uri = Uri()
        application_service = ApplicationService(spaces=spaces, uri=uri)
        ret = application_service.cb_get_application(Uri('test/uri'), Spaces.ACTION_DELETE, None)
        self.assertEqual(None, ret)

    def test_cb_get_application_remove(self):
        spaces = Spaces()
        uri = Uri()
        application_service = ApplicationService(spaces=spaces, uri=uri)
        res = application_service.cb_get_application(Uri('test/uri'), Spaces.ACTION_REMOVE, None)
        self.assertEqual(None, res)
        
    def test_cb_get_application_exits(self):
        spaces = Spaces()
        uri = Uri()
        application_service = ApplicationService(spaces=spaces, uri=uri)
        bool = application_service.cb_get_application(Uri('test/uri'), Spaces.ACTION_EXISTS, None)
        self.assertFalse(bool)

    def test_cb_get_application_find(self):
        spaces = Spaces()
        uri = Uri()
        application_service = ApplicationService(spaces=spaces, uri=uri)
        lst = application_service.cb_get_application(Uri('test/uri'), Spaces.ACTION_FIND, None)
        self.assertEqual(None, lst)

def raw_xml(xml_str):
    xml = minidom.parseString(xml_str)
    return u''.join([unicode(line).strip() for line in xml.toprettyxml().splitlines()])

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']
    unittest.main()